<template>
  <div class="product-detail">
    <div v-if="loading" class="loading-container">
      <p>正在加载商品信息...</p>
    </div>

    <div v-else-if="!product" class="error-container">
      <p>商品不存在或已下架</p>
      <button @click="goBack" class="back-button">返回商品列表</button>
    </div>

    <div v-else class="detail-content">
      <!-- 商品信息头部 -->
      <div class="detail-header">
        <button @click="goBack" class="back-button">← 返回</button>
        <!-- 浏览次数显示在右上角 -->
        <div class="view-count">
          <span class="icon">👁</span>
          <span class="count">{{ product.viewCount || 0 }}</span>
          <span>次浏览</span>
        </div>
      </div>

      <!-- 商品主体内容 -->
        <div class="product-main">
          <!-- 商品图片 - 使用Carousel走马灯 -->
          <div class="product-image-section">
            <el-carousel
              v-if="carouselImages.length > 0"
              height="400px"
              :interval="5000"
              arrow="hover"
              indicator-position="bottom"
              class="product-carousel"
            >
              <el-carousel-item v-for="(img, index) in carouselImages" :key="index">
                <img
                  :src="img.url"
                  :alt="img.alt"
                  class="carousel-image"
                />
              </el-carousel-item>
            </el-carousel>
            <div v-else class="no-image">暂无图片</div>
          </div>

          <!-- 商品信息 -->
          <div class="product-info">
            <h1 class="product-name">{{ product.name }}</h1>
            <div class="product-price">￥{{ displayPrice }}</div>

            <!-- 规格标签 -->
            <div class="product-sku-section" v-if="skuList.length > 0">
              <div class="sku-label">规格：</div>
              <div class="sku-tags">
                <span
                  v-for="sku in skuList"
                  :key="sku.id"
                  class="sku-tag"
                  :class="{ active: selectedSku && selectedSku.id === sku.id, disabled: sku.stock === 0 || sku.status === 0 }"
                  @click="(sku.stock === 0 || sku.status === 0) ? null : selectSku(sku)"
                >
                  {{ sku.name }}
                </span>
              </div>
              <!-- 规格库存显示 -->
              <div class="sku-stock">
                库存：<span class="stock-value">{{ displayStock }}</span> 件
              </div>
              <!-- 数量选择器 -->
              <div class="quantity-selector">
                <div class="quantity-label">数量：</div>
                <div class="quantity-control">
                  <button
                    class="quantity-btn decrease"
                    @click="purchaseQuantity = Math.max(1, purchaseQuantity - 1)"
                    :disabled="purchaseQuantity <= 1"
                  >
                    -
                  </button>
                  <input
                    type="number"
                    v-model.number="purchaseQuantity"
                    min="1"
                    :max="displayStock"
                    class="quantity-input"
                  >
                  <button
                    class="quantity-btn increase"
                    @click="purchaseQuantity = Math.min(displayStock, purchaseQuantity + 1)"
                    :disabled="purchaseQuantity >= displayStock"
                  >
                    +
                  </button>
                </div>
              </div>
            </div>

            <!-- 价格标签 -->
            <!-- 登录提示 -->
            <div v-if="!isLoggedIn" class="login-prompt">
              <div class="prompt-icon">🔐</div>
              <div class="prompt-text">
                <h3>登录后享受更多服务</h3>
                <p>登录后可以加入购物车、立即购买，享受更便捷的购物体验</p>
              </div>
              <div class="prompt-actions">
                <button class="login-btn" @click="goToLogin">立即登录</button>
                <button class="register-btn" @click="goToRegister">注册账号</button>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div v-else class="action-buttons">
              <button class="add-to-cart" @click="handleAddToCart">加入购物车</button>
              <button
                class="buy-now"
                @click="handleBuyNow"
                :disabled="!selectedSku || purchaseQuantity <= 0 || orderLoading"
              >
                <span v-if="orderLoading">下单中...</span>
                <span v-else>立即购买</span>
              </button>
            </div>
          </div>
        </div>

      <!-- 商品描述 - 独立区域 -->
      <div class="product-description">
        <h2>商品描述</h2>
        <div class="description-content">
          {{ product.description || '暂无描述' }}
        </div>
      </div>

      <!-- 店铺信息 -->
      <div class="shop-info">
        <h2>店铺信息</h2>
        <div class="shop-header">
          <img v-if="product.logoUrl" :src="product.logoUrl" :alt="product.shopName" class="shop-logo" />
          <div class="shop-details">
            <div class="shop-name">{{ product.shopName || '未知店铺' }}</div>
            <div class="shop-contact">联系电话：{{ product.contactPhone || '暂无' }}</div>
            <div class="shop-address">店铺地址：{{ product.address || '暂无' }}</div>
            <button
              v-if="product.sellerId"
              class="enter-shop-btn"
              @click="goToSellerPage(product.sellerId)"
            >
              进入商铺
            </button>
          </div>
        </div>
      </div>
      <!-- 商品详情 -->
      <div class="product-details">
        <h2>商品详情</h2>
        <!-- <div class="detail-item">
          <span class="label">商品ID：</span>
          <span class="value">{{ product.id }}</span>
        </div> -->
        <div class="detail-item">
          <span class="label">商品名称：</span>
          <span class="value">{{ product.name }}</span>
        </div>
        <div class="detail-item">
          <span class="label">商品价格：</span>
          <span class="value">￥{{ product.price }}起</span>
        </div>
        <div class="detail-item">
          <span class="label">商品分类：</span>
          <span class="value">{{ product.categoryName || '暂无' }}</span>
        </div>
        <div class="detail-item">
          <span class="label">商品库存：</span>
          <span class="value">{{ product.stock }} 件</span>
        </div>
        <!-- <div class="detail-item">
          <span class="label">卖家ID：</span>
          <span class="value">{{ product.sellerId || '暂无' }}</span>
        </div> -->
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="showError" class="error-toast">
      <div class="error-content">
        <span class="error-icon">⚠</span>
        <span class="error-text">{{ errorMessage }}</span>
      </div>
    </div>

    <!-- 地址确认弹窗 -->
    <div v-if="showAddressConfirm" class="address-confirm-modal" @click="closeAddressConfirm">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>确认收货地址</h3>
          <button class="close-btn" @click="closeAddressConfirm">×</button>
        </div>
        <div class="modal-body">
          <div class="address-section">
            <div class="address-label">
              <span class="icon">📍</span>
              <span>收货地址</span>
            </div>
            <div class="address-input-container">
              <textarea
                v-model="editableAddress"
                class="address-input"
                placeholder="请输入详细的收货地址"
                rows="3"
                :disabled="addressLoading"
              ></textarea>
            </div>
            <div class="address-tips">
              <span class="tip-icon">💡</span>
              <span>请确认地址信息准确无误，以免影响商品配送</span>
            </div>
          </div>
          <div class="order-summary">
            <div class="summary-item">
              <span class="label">商品：</span>
              <span class="value">{{ product?.name }}</span>
            </div>
            <div class="summary-item">
              <span class="label">数量：</span>
              <span class="value">{{ purchaseQuantity }}件</span>
            </div>
            <div class="summary-item total">
              <span class="label">总金额：</span>
              <span class="value price">￥{{ (displayPrice * purchaseQuantity).toFixed(2) }}</span>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeAddressConfirm" :disabled="orderLoading">
            取消
          </button>
          <button class="confirm-btn" @click="confirmAddressAndOrder" :disabled="orderLoading || !editableAddress.trim()">
            <span v-if="orderLoading" class="loading-spinner"></span>
            {{ orderLoading ? '下单中...' : '确认下单' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 订单成功弹窗 -->
    <div v-if="orderSuccess" class="order-success-modal" @click="closeOrderSuccess">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>下单成功！</h3>
          <button class="close-btn" @click="closeOrderSuccess">×</button>
        </div>
        <div class="modal-body">
          <div class="success-icon">✓</div>
          <div class="order-info">
            <div class="info-item">
              <span class="label">订单号：</span>
              <span class="value">{{ orderResult?.orderId }}</span>
            </div>
            <div class="info-item">
              <span class="label">收货人：</span>
              <span class="value">{{ orderResult?.customerName || '用户' }}</span>
            </div>
            <div class="info-item">
              <span class="label">商品名称：</span>
              <span class="value">{{ orderResult?.productName }}</span>
            </div>
            <div class="info-item">
              <span class="label">订单金额：</span>
              <span class="value price">￥{{ orderResult?.totalPrice }}</span>
            </div>
            <div class="info-item">
              <span class="label">下单时间：</span>
              <span class="value">{{ orderResult?.createTime }}</span>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="continue-btn" @click="closeOrderSuccess">继续购物</button>
          <button class="view-order-btn" @click="viewOrderDetail">查看订单</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import http from '@/api/http'
import { incrementProductViewCount } from '../api/seller'
import { ElMessage } from 'element-plus'
import { addToCart, getCartListByCustomerId, updateCartItem } from '../api/user'

export default {
  name: 'ProductDetail',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const product = ref(null)
    const loading = ref(true)
    const skuList = ref([])
    const selectedSku = ref(null)
    const displayPrice = computed(() => selectedSku.value?.price || product.value?.price)
    const displayStock = computed(() => selectedSku.value?.stock || product.value?.stock)
    const purchaseQuantity = ref(1)

    // 订单相关状态
    const orderLoading = ref(false)
    const orderSuccess = ref(false)
    const orderResult = ref(null)// 错误处理状态
    const errorMessage = ref('')
    const showError = ref(false)
    // Track which products have been viewed to avoid duplicate view counts
    const viewedProducts = ref(new Set())

    // 地址确认弹窗状态
    const showAddressConfirm = ref(false)
    const customerAddress = ref('')
    const editableAddress = ref('')
    const addressLoading = ref(false)

    // 倒计时相关状态
    const countdownTime = ref(20 * 60) // 20分钟 = 1200秒
    const countdownTimer = ref(null)
    const isCountdownActive = ref(false)

    // 合并主图和图集为carousel数据
    const carouselImages = computed(() => {
      const images = []
      // 添加主图
      if (product.value?.image) {
        images.push({
          url: product.value.image,
          alt: product.value.name
        })
      }
      // 添加图集
      if (product.value?.productImages && product.value.productImages.length > 0) {
        product.value.productImages.forEach((img, index) => {
          if (img.url) {
            images.push({
              url: img.url.trim().replace(/`/g, ''),
              alt: `${product.value.name} 图片${index + 1}`
            })
          }
        })
      }
      return images
    })

    // 防重复请求SKU标志
    let isLoadingSku = false
    let currentSkuProductId = null

    // 获取商品规格
    const fetchProductSku = async (productId) => {
      // 防止重复请求同一个商品的SKU
      if (isLoadingSku && currentSkuProductId === productId) {
        console.log('正在加载商品规格，跳过重复请求')
        return
      }

      isLoadingSku = true
      currentSkuProductId = productId

      try {
        const response = await axios.get(`/api/product/queryByPId/${productId}`)
        if (response.data && Array.isArray(response.data)) {
          skuList.value = response.data
          // 默认选择第一个可点击的规格
          if (skuList.value.length > 0) {
            const firstAvailableSku = skuList.value.find(sku => sku.stock > 0 && sku.status === 1)
            selectedSku.value = firstAvailableSku || null
          }
        }
      } catch (error) {
        console.error('获取商品规格失败:', error)
      } finally {
        isLoadingSku = false
      }
    }

    // 防重复请求标志
    let isLoadingProduct = false
    let currentProductId = null

    // 获取商品详情
    const fetchProductDetail = async () => {
      const productId = route.params.id
      if (!productId) {
        loading.value = false
        return
      }

      // 防止重复请求同一个商品
      if (isLoadingProduct && currentProductId === productId) {
        console.log('正在加载商品详情，跳过重复请求')
        return
      }

      // 如果是不同的商品ID，允许请求
      if (currentProductId !== productId) {
        currentProductId = productId
      }

      isLoadingProduct = true
      loading.value = true

      try {
        const response = await axios.get(`/api/product/queryMessageById/${productId}`)
        if (response.data) {
          console.log('获取商品详情成功:', response.data)
            product.value = {
              ...response.data,
              image: response.data.image ? response.data.image.trim().replace(/`/g, '') : '',
              logoUrl: response.data.logoUrl ? response.data.logoUrl.trim().replace(/`/g, '') : ''
            }
            // 获取商品规格
            await fetchProductSku(productId)

            // 只在首次访问商品时调用浏览量统计接口
            if (!viewedProducts.value.has(productId)) {
              try {
                await incrementProductViewCount(productId)
                viewedProducts.value.add(productId)
                console.log('商品浏览量+1成功')
                // 更新本地显示的浏览量
                if (product.value.viewCount !== undefined) {
                  product.value.viewCount = (product.value.viewCount || 0) + 1
                }
              } catch (viewError) {
                console.error('增加商品浏览量失败:', viewError)
                // 浏览量统计失败不影响主页面展示
              }
            }
        }
      } catch (error) {
          console.error('获取商品详情失败:', error)
        } finally {
          loading.value = false
        }
    }

    // 选择规格
    const selectSku = (sku) => {
      selectedSku.value = sku
    }

    // 进入商家页面
    const goToSellerPage = (sellerId) => {
      router.push(`/seller/${sellerId}`)
    }

    // 返回上一页
    const goBack = () => {
      // 检查是否有保存的状态，如果有则跳转到首页并标记需要恢复状态
      const savedState = sessionStorage.getItem('homeShopState')
      if (savedState) {
        // 标记需要恢复状态
        sessionStorage.setItem('shouldRestoreState', 'true')
        router.push('/')
      } else {
        // 没有保存状态，使用默认返回
        router.back()
      }
    }

    // 显示错误提示
    const showErrorMessage = (message) => {
      errorMessage.value = message
      showError.value = true
      setTimeout(() => {
        showError.value = false
      }, 3000)
    }

    // 获取顾客地址
    const fetchCustomerAddress = async (customerId) => {
      try {
        addressLoading.value = true

        const response = await http.get(`/customer/queryCustomerAddress?customerId=${customerId}`)
        
        if ( response) {
          const address = response
          console.log('获取顾客地址响应:', response)
          customerAddress.value = address
          editableAddress.value = address
          console.log(editableAddress.value)
          return address
        } else {
          console.log('用户暂无设置地址')
          return null
        }
      } catch (error) {
        if (error.response?.status === 404) {
          console.log('用户暂无设置地址')
          return null
        }
        console.error('获取顾客地址失败:', error)
        showErrorMessage('获取地址失败，请稍后重试')
        return null
      } finally {
        addressLoading.value = false
      }
    }

    // 关闭地址确认弹窗
    const closeAddressConfirm = () => {
      showAddressConfirm.value = false
      editableAddress.value = customerAddress.value
    }

    // 确认地址并创建订单
    const confirmAddressAndOrder = async () => {
      if (!editableAddress.value.trim()) {
        showErrorMessage('请输入收货地址')
        return
      }

      // 从localStorage获取用户信息
      const userToken = localStorage.getItem('userToken')
      const userRoles = JSON.parse(localStorage.getItem('userRoles') || '[]')
      
      if (!userToken || userRoles.length === 0) {
        showErrorMessage('用户未登录，请重新登录')
        return
      }

      // 从角色数组中获取CUSTOMER角色的ID
      const customerRole = userRoles.find(role => role.code === 'CUSTOMER')
      const customerId = customerRole ? customerRole.id : null
      
      if (!customerId) {
        showErrorMessage('无法获取用户信息，请重新登录')
        return
      }

      const orderData = {
        customerId: customerId,
        totalPrice: displayPrice.value * purchaseQuantity.value,
        orderItemDTOS: [{
          sellerId: product.value.sellerId,
          skuId: selectedSku.value.id,
          productId: product.value.id,
          address: editableAddress.value.trim(), // 使用用户确认的地址
          productName: product.value.name,
          quantity: purchaseQuantity.value,
          price: displayPrice.value
        }]
      }

      orderLoading.value = true
      showAddressConfirm.value = false

      try {
        // 获取token用于请求认证
        const token = localStorage.getItem('userToken')
        if (!token) {
          showErrorMessage('用户未登录，请重新登录')
          return
        }

        const response = await http.post('/orders/addOrder', orderData)

        if (response) {
          const result = response
          orderResult.value = result

          // 订单创建成功后直接跳转到订单详情页面
          if (result?.orderId) {
            router.push(`/order/${result.orderId}`)
          } else {
            // 如果没有订单ID，显示成功弹窗
            orderSuccess.value = true
          }
        } else {
          showErrorMessage(response.info || '下单失败，请稍后重试')
        }
      } catch (error) {
         console.error('下单失败:', error)
         const errorMessage = error.response?.data?.message || '下单失败，请稍后重试'
         showErrorMessage(errorMessage)
       } finally {
        orderLoading.value = false
      }
    }

    // 立即购买功能
    const handleBuyNow = async () => {
      // 清除之前的错误信息
      showError.value = false

      if (!selectedSku.value) {
        showErrorMessage('请选择商品规格')
        return
      }

      if (purchaseQuantity.value <= 0 || purchaseQuantity.value > displayStock.value) {
        showErrorMessage('购买数量不正确')
        return
      }

      if (!product.value?.sellerId) {
        showErrorMessage('商品信息不完整，无法下单')
        return
      }

      // 检查用户登录状态
      const userToken = localStorage.getItem('userToken')
      const userRoles = JSON.parse(localStorage.getItem('userRoles') || '[]')

      if (!userToken || userRoles.length === 0) {
        showErrorMessage('请先登录后再购买')
        return
      }

      // 从角色数组中获取CUSTOMER角色的ID
      const customerRole = userRoles.find(role => role.code === 'CUSTOMER')
      const customerId = customerRole ? customerRole.id : null

      console.log('购买检查 - userRoles:', userRoles)
      console.log('购买检查 - customerRole:', customerRole)
      console.log('购买检查 - 获取的customerId:', customerId)

      if (!customerId) {
        console.log('错误 - 无法获取customerId，用户可能没有CUSTOMER角色')
        showErrorMessage('无法获取顾客ID，请确认您有购买权限或重新登录')
        return
      }

      // 获取用户地址并显示确认弹窗
      const address = await fetchCustomerAddress(customerId)
    
      // 无论是否成功获取地址，都显示地址确认弹窗
      if (address) {
        // 如果获取地址成功，确保editableAddress被正确设置
        customerAddress.value = address
        editableAddress.value = address
      } else {
        // 如果获取地址失败，清空地址字段让用户手动输入
        customerAddress.value = ''
        editableAddress.value = ''
      }

      showAddressConfirm.value = true
    }

    // 关闭订单成功弹窗
    const closeOrderSuccess = () => {
      orderSuccess.value = false
      orderResult.value = null
    }

    // 查看订单详情
    const viewOrderDetail = () => {
      if (orderResult.value?.orderId) {
        // 跳转到订单详情页面，这里需要根据实际的路由配置
        router.push(`/order/${orderResult.value.orderId}`)
      }
      closeOrderSuccess()
    }

    // 监听路由参数变化
    watch(() => route.params.id, (newId, oldId) => {
      if (newId && newId !== oldId) {
        fetchProductDetail()
      }
    })

    // 获取顾客ID
    const getCustomerId = () => {
      // 从userRoles数组中获取customerId
      const userRolesStr = localStorage.getItem('userRoles')
      if (userRolesStr) {
        try {
          const userRoles = JSON.parse(userRolesStr)
          const customerRole = userRoles.find(role => role.code === 'CUSTOMER')
          return customerRole ? Number(customerRole.id) : null
        } catch (error) {
          console.error('解析userRoles失败:', error)
          return null
        }
      }
      return null
    }

    // 加入购物车
    const handleAddToCart = async () => {
      // 检查是否登录
      const customerId = getCustomerId()
      if (!customerId) {
        ElMessage.warning('请先登录')
        return
      }

      // 检查是否选择规格
      if (!selectedSku.value) {
        ElMessage.warning('请选择商品规格')
        return
      }

      // 基本数量验证
      if (purchaseQuantity.value <= 0) {
        ElMessage.warning('请选择有效数量')
        return
      }

      try {
        // 先获取购物车列表，检查是否已存在相同规格商品
        const cartResponse = await getCartListByCustomerId(Number(customerId))
        const cartItems = cartResponse && cartResponse.list ? cartResponse.list : []

        // 查找相同规格的商品
        const existingItem = cartItems.find(item => item.skuId === selectedSku.value.id)
        
        // 计算购物车中已有的相同SKU数量（不包括当前要添加的数量）
        const existingQuantity = existingItem ? existingItem.quantity : 0
        
        // 计算可用库存（总库存 - 购物车中已有的相同SKU数量）
        const availableStock = Math.max(0, displayStock.value - existingQuantity)
        
        // 检查要添加的数量是否超过可用库存
        if (purchaseQuantity.value > availableStock) {
          if (availableStock > 0) {
            ElMessage.warning(`超过库存限制，考虑您购物车中已有的${existingQuantity}件，该商品最多还能添加${availableStock}件`)
            // 调整购买数量为可用库存
            purchaseQuantity.value = availableStock
            return
          } else {
            ElMessage.warning(`库存不足，考虑您购物车中已有的${existingQuantity}件，该商品暂无可用库存`)
            return
          }
        }

        if (existingItem) {
          // 已存在，更新数量
          const newQuantity = existingQuantity + purchaseQuantity.value

          await updateCartItem({
            id: existingItem.id,
            skuId: selectedSku.value.id,
            quantity: newQuantity
          })
          ElMessage.success(`购物车商品数量已更新为${newQuantity}件`)
        } else {
          // 不存在，添加新商品
          await addToCart({
            customerId: Number(customerId),
            skuId: selectedSku.value.id,
            quantity: purchaseQuantity.value
          })
          ElMessage.success('加入购物车成功')
        }
      } catch (error) {
        console.error('加入购物车失败:', error)
        ElMessage.error('加入购物车失败，请重试')
      }
    }

    // 检查登录状态
    const isLoggedIn = computed(() => {
      const userToken = localStorage.getItem('userToken')
      const userRoles = JSON.parse(localStorage.getItem('userRoles') || '[]')
      return !!(userToken && userRoles.length > 0)
    })

    // 跳转到登录页面
    const goToLogin = () => {
      router.push('/customer-login')
    }

    // 跳转到注册页面
    const goToRegister = () => {
      router.push('/customer-register')
    }

    onMounted(() => {
      fetchProductDetail()
    })

    return {
      product,
      loading,
      goBack,
      carouselImages,
      skuList,
      selectedSku,
      displayPrice,
      displayStock,
      purchaseQuantity,
      selectSku,
      goToSellerPage,
      handleAddToCart,
      handleBuyNow,
      orderLoading,
      orderSuccess,
      orderResult,
      closeOrderSuccess,
      viewOrderDetail,
      errorMessage,
      showError,
      showAddressConfirm,
      customerAddress,
      editableAddress,
      addressLoading,
      closeAddressConfirm,
      confirmAddressAndOrder,
      isLoggedIn,
      goToLogin,
      goToRegister
    }
  }
}
</script>

<style scoped>
.product-detail {
  width: 100%;
  height: 94.3vh;
  padding: 20px;
  background-color: #fffffe;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
  gap: 20px;
}

.detail-header {
  margin-bottom: 20px;
}

.back-button {
  padding: 8px 16px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.back-button:hover {
  background-color: #2980b9;
}

.detail-content {
  max-width: 1200px;
  height: 94.3vh;
  margin: 0 auto;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow-y: auto; /* 允许垂直滚动 */
  position: relative;
}

/* 浏览次数样式 */
.view-count {
  position: absolute;
  top: 20px;
  right: 30px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  padding: 12px 20px;
  border-radius: 25px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  font-size: 14px;
  color: #495057;
  display: flex;
  align-items: center;
  gap: 8px;
  z-index: 10;
  border: 1px solid rgba(52, 152, 219, 0.2);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.view-count:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 25px rgba(0, 0, 0, 0.2);
  border-color: #3498db;
}

.view-count .icon {
  font-size: 18px;
  color: #3498db;
  background: rgba(52, 152, 219, 0.1);
  padding: 4px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.view-count .count {
  font-weight: 600;
  color: #2c3e50;
}

/* 商品描述区域样式 */
.product-description-section {
  padding: 40px 30px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 1px solid #dee2e6;
  position: relative;
}

.product-description-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #3498db, #2ecc71, #f39c12, #e74c3c);
}

.description-title {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 12px;
  position: relative;
}

.description-title::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 0;
  width: 60px;
  height: 3px;
  background: linear-gradient(90deg, #3498db, #2ecc71);
  border-radius: 2px;
}

.description-title .icon {
  font-size: 26px;
  color: #3498db;
  background: rgba(52, 152, 219, 0.1);
  padding: 8px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.description-content {
  font-size: 16px;
  line-height: 1.8;
  color: #495057;
  background: white;
  padding: 30px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  white-space: pre-wrap;
  position: relative;
  overflow: hidden;
}

.description-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: linear-gradient(180deg, #3498db, #2ecc71);
}

.sku-tag.disabled {
  background-color: #e0e0e0;
  color: #a0a0a0;
  cursor: not-allowed;
  border-color: #d0d0d0;
}

.sku-tag.disabled:hover {
  background-color: #e0e0e0;
  color: #a0a0a0;
  border-color: #d0d0d0;
}
.detail-content::-webkit-scrollbar {
  width: 8px;
}

.detail-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.detail-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
  transition: background 0.3s;
}

.detail-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.product-main {
  display: flex;
  padding: 30px;
  gap: 30px;
  border-bottom: 1px solid #eee;
}

.product-image-section {
  width: 40%;
  min-width: 300px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-carousel {
  width: 100%;
  height: 400px;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  max-height: 400px;
}

/* 自定义走马灯指示器样式 */
:deep(.el-carousel__indicator.is-active button) {
  background-color: #3498db;
  width: 20px;
}

:deep(.el-carousel__indicator button) {
  width: 20px;
  transition: width 0.3s;
}

/* 自定义走马灯箭头样式 */
:deep(.el-carousel__arrow) {
  background-color: rgba(0, 0, 0, 0.3);
  width: 40px;
  height: 40px;
}

:deep(.el-carousel__arrow:hover) {
  background-color: rgba(0, 0, 0, 0.5);
}

.no-image {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 300px;
  background-color: #eee;
  color: #999;
  font-size: 16px;
  border-radius: 8px;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.product-name {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.product-price {
  font-size: 32px;
  font-weight: 700;
  color: #e74c3c;
  margin-bottom: 15px;
}

/* 规格库存显示样式 */
.sku-stock {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

.stock-value {
  font-weight: 500;
  color: #27ae60;
  margin: 0 5px;
}

/* 数量选择器样式 */
.quantity-selector {
  margin-top: 15px;
  display: flex;
  align-items: center;
}

.quantity-label {
  font-size: 14px;
  color: #666;
  margin-right: 10px;
}

.quantity-control {
  display: flex;
  align-items: center;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.quantity-btn {
  width: 32px;
  height: 32px;
  border: none;
  background-color: #f5f5f5;
  color: #333;
  font-size: 18px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.quantity-btn:hover:not(:disabled) {
  background-color: #e8e8e8;
}

.quantity-btn:disabled {
  cursor: not-allowed;
  opacity: 0.5;
  background-color: #f9f9f9;
}

.quantity-input {
  width: 60px;
  height: 32px;
  border: none;
  text-align: center;
  font-size: 14px;
  outline: none;
  -moz-appearance: textfield;
}

.quantity-input::-webkit-outer-spin-button,
.quantity-input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* 规格标签样式 */
.product-sku-section {
  margin: 15px 0;
}

.sku-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
  font-weight: 500;
}

.sku-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.sku-tag {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #333;
  background-color: #fff;
  transition: all 0.3s;
}

.sku-tag:hover {
  border-color: #3498db;
  color: #3498db;
}

.sku-tag.active {
  border-color: #3498db;
  background-color: #3498db;
  color: #fff;
}

.product-stock,
.product-view {
  font-size: 14px;
  color: #666;
  margin-top: 8px;
}

.product-description {
  flex: 1;
  margin-top: 15px;
}

.product-description h3 {
  font-size: 18px;
  margin-bottom: 10px;
  color: #333;
}

.product-description p {
  color: #666;
  line-height: 1.6;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.add-to-cart,
.buy-now {
  flex: 1;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.add-to-cart {
  background-color: #f39c12;
  color: white;
}

.add-to-cart:hover {
  background-color: #e67e22;
}

.buy-now {
  background-color: #e74c3c;
  color: white;
}

.buy-now:hover {
  background-color: #c0392b;
}

/* 登录提示样式 */
.login-prompt {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 24px;
  text-align: center;
  color: white;
  margin-top: 20px;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.prompt-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.9;
}

.prompt-text h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
}

.prompt-text p {
  margin: 0 0 20px 0;
  font-size: 14px;
  opacity: 0.9;
  line-height: 1.5;
}

.prompt-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.login-btn, .register-btn {
  padding: 10px 24px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 100px;
}

.login-btn {
  background-color: white;
  color: #667eea;
}

.login-btn:hover {
  background-color: #f8f9ff;
  transform: translateY(-1px);
}

.register-btn {
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.register-btn:hover {
  background-color: rgba(255, 255, 255, 0.3);
  transform: translateY(-1px);
}

.shop-info {
  padding: 30px;
  border-top: 1px solid #eee;
  background-color: #fafafa;
}

.shop-info h2 {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
  border-bottom: 2px solid #3498db;
  padding-bottom: 10px;
}

.shop-header {
  display: flex;
  align-items: center;
  gap: 20px;
}

.shop-logo {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #ddd;
}

.shop-details {
  display: flex;
  flex-direction: column;
  gap: 10px;
  flex: 1;
  justify-content: space-between;
}

.enter-shop-btn {
  margin-top: 15px;
  padding: 8px 20px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.enter-shop-btn:hover {
  background-color: #2980b9;
}

.shop-name {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.shop-contact,
.shop-address {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}



.product-details {
  padding: 40px 30px;
  background: white;
  border-top: none;
  position: relative;
}

.product-details::before {
  content: '';
  position: absolute;
  top: 0;
  left: 30px;
  right: 30px;
  height: 1px;
  background: linear-gradient(90deg, transparent, #dee2e6, transparent);
}

.product-details h2 {
  font-size: 26px;
  font-weight: 700;
  margin-bottom: 30px;
  color: #2c3e50;
  position: relative;
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-details h2::before {
  content: '📋';
  font-size: 28px;
  background: rgba(52, 152, 219, 0.1);
  padding: 8px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-details h2::after {
  content: '';
  position: absolute;
  bottom: -12px;
  left: 0;
  width: 80px;
  height: 3px;
  background: linear-gradient(90deg, #3498db, #2ecc71);
  border-radius: 2px;
}

.detail-item {
  display: flex;
  padding: 18px 24px;
  margin-bottom: 12px;
  background: #f8f9fa;
  border-radius: 10px;
  border: 1px solid #e9ecef;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.detail-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background: linear-gradient(180deg, #3498db, #2ecc71);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.detail-item:hover {
  background: #ffffff;
  border-color: #3498db;
  box-shadow: 0 4px 15px rgba(52, 152, 219, 0.1);
  transform: translateY(-2px);
}

.detail-item:hover::before {
  opacity: 1;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-item .label {
  width: 140px;
  font-weight: 600;
  color: #495057;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  font-size: 15px;
}

.detail-item .label::after {
  content: '';
  width: 6px;
  height: 6px;
  background: #3498db;
  border-radius: 50%;
  margin-left: 8px;
  margin-right: 8px;
}

.detail-item .value {
  flex: 1;
  color: #2c3e50;
  font-weight: 500;
  font-size: 15px;
  line-height: 1.5;
}

.detail-item .value.price {
  color: #e74c3c;
  font-weight: 700;
  font-size: 16px;
}

.detail-item.full-width {
  flex-direction: column;
}

.detail-item.full-width .label {
  width: 100%;
  margin-bottom: 12px;
}

.detail-item.full-width .value {
  margin-top: 0;
  line-height: 1.8;
  padding: 15px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .product-main {
    flex-direction: column;
    padding: 20px;
  }

  .product-image-section {
    min-height: 200px;
  }

  .product-name {
    font-size: 24px;
  }

  .product-price {
    font-size: 28px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .detail-item {
    flex-direction: column;
    padding: 15px 20px;
  }

  .detail-item .label {
    width: 100%;
    margin-bottom: 8px;
  }

  .detail-item .label::after {
    display: none;
  }

  .shop-header {
    flex-direction: column;
    align-items: flex-start;
  }

  /* 移动端浏览次数样式 */
  .view-count {
    top: 15px;
    right: 20px;
    padding: 8px 16px;
    font-size: 13px;
  }

  .view-count .icon {
    font-size: 16px;
    padding: 3px;
  }

  /* 移动端商品描述样式 */
  .product-description-section {
    padding: 30px 20px;
  }

  .description-title {
    font-size: 20px;
    gap: 8px;
  }

  .description-title .icon {
    font-size: 22px;
    padding: 6px;
  }

  .description-content {
    padding: 20px;
    font-size: 15px;
  }

  /* 移动端商品详情样式 */
  .product-details {
    padding: 30px 20px;
  }

  .product-details h2 {
    font-size: 22px;
    gap: 8px;
  }

  .product-details h2::before {
    font-size: 24px;
    padding: 6px;
  }

  .shop-logo {
    width: 60px;
    height: 60px;
  }
}

/* 错误提示样式 */
.error-toast {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 2000;
  animation: slideInRight 0.3s ease-out;
}

.error-content {
  background: linear-gradient(135deg, #e74c3c, #c0392b);
  color: white;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(231, 76, 60, 0.3);
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 300px;
  max-width: 400px;
}

.error-icon {
  font-size: 18px;
  flex-shrink: 0;
}

.error-text {
  font-size: 14px;
  font-weight: 500;
  line-height: 1.4;
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(100%);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 订单成功弹窗样式 */
.order-success-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-50px) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #eee;
  background: linear-gradient(135deg, #27ae60, #2ecc71);
  color: white;
  border-radius: 12px 12px 0 0;
}

.modal-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: white;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.3s;
}

.close-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.modal-body {
  padding: 30px 24px;
  text-align: center;
}

.success-icon {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #27ae60, #2ecc71);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40px;
  color: white;
  margin: 0 auto 30px;
  animation: successPulse 0.6s ease-out;
}

@keyframes successPulse {
  0% {
    transform: scale(0);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

.order-info {
  text-align: left;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item .label {
  font-weight: 500;
  color: #666;
  font-size: 14px;
}

.info-item .value {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.info-item .value.price {
  color: #e74c3c;
  font-size: 16px;
}

.modal-footer {
  padding: 20px 24px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.continue-btn,
.view-order-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.continue-btn {
  background-color: #95a5a6;
  color: white;
}

.continue-btn:hover {
  background-color: #7f8c8d;
}

.view-order-btn {
  background-color: #3498db;
  color: white;
}

.view-order-btn:hover {
  background-color: #2980b9;
}

/* 地址确认弹窗样式 */
.address-confirm-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease-out;
}

.address-confirm-modal .modal-content {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  animation: slideInUp 0.3s ease-out;
}

.address-section {
  margin-bottom: 20px;
}

.address-label {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-weight: 600;
  color: #2c3e50;
  font-size: 16px;
}

.address-label .icon {
  margin-right: 8px;
  font-size: 18px;
}

.address-input-container {
  margin-bottom: 12px;
}

.address-input {
  width: 100%;
  padding: 12px;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.5;
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
  transition: border-color 0.3s;
}

.address-input:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}

.address-input:disabled {
  background-color: #f8f9fa;
  cursor: not-allowed;
}

.address-tips {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  font-size: 13px;
  color: #6c757d;
}

.address-tips .tip-icon {
  margin-right: 6px;
  font-size: 14px;
}

.order-summary {
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  margin-top: 20px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.summary-item:last-child {
  margin-bottom: 0;
}

.summary-item.total {
  border-top: 1px solid #dee2e6;
  padding-top: 12px;
  margin-top: 12px;
  font-weight: 600;
  font-size: 16px;
}

.summary-item .label {
  color: #6c757d;
}

.summary-item .value {
  color: #2c3e50;
  font-weight: 500;
}

.summary-item .value.price {
  color: #e74c3c;
  font-weight: 600;
}

.address-confirm-modal .modal-footer {
  display: flex;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #e1e8ed;
}

.cancel-btn,
.confirm-btn {
  flex: 1;
  padding: 12px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.cancel-btn {
  background-color: #6c757d;
  color: white;
}

.cancel-btn:hover:not(:disabled) {
  background-color: #5a6268;
}

.confirm-btn {
  background-color: #28a745;
  color: white;
}

.confirm-btn:hover:not(:disabled) {
  background-color: #218838;
}

.confirm-btn:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式弹窗 */
@media (max-width: 768px) {
  .modal-content {
    width: 95%;
    margin: 20px;
  }

  .modal-footer {
    flex-direction: column;
  }

  .continue-btn,
  .view-order-btn {
    width: 100%;
  }

  .address-confirm-modal .modal-content {
    width: 95%;
    margin: 10px;
  }

  .address-confirm-modal .modal-footer {
    flex-direction: column;
  }

  .cancel-btn,
  .confirm-btn {
    width: 100%;
  }

  /* 登录提示响应式样式 */
  .login-prompt {
    padding: 20px;
    margin-top: 16px;
  }

  .prompt-icon {
    font-size: 40px;
    margin-bottom: 12px;
  }

  .prompt-text h3 {
    font-size: 18px;
  }

  .prompt-text p {
    font-size: 13px;
    margin-bottom: 16px;
  }

  .prompt-actions {
    flex-direction: column;
    gap: 8px;
  }

  .login-btn, .register-btn {
    width: 100%;
    padding: 12px 24px;
  }
}
</style>
